<?php
/**
 * Created by PhpStorm.
 * User: AivyYuan
 * Date: 2016/7/14
 * Time: 15:00
 */
namespace app\controllers;
use app\models\LoginForm;
use app\models\RegisterForm;
use yii\helpers\Url;
use yii\web\Controller;

class UserController extends Controller{
    public $layout = "user";
    public function actionRegister(){
        if(\Yii::$app->request->isPost){
            $register_form = new RegisterForm();

            $post_data[] = \Yii::$app->request->post();
            
            $register_form->username = \Yii::$app->request->post('username');
            $register_form->password = \Yii::$app->request->post('password');
            $register_form->password_repeat = \Yii::$app->request->post('password_repeat');
            $register_form->email = \Yii::$app->request->post('email');
            if($register_form->validate()){
               $register_form->password = \Yii::$app->getSecurity()->generatePasswordHash(\Yii::$app->request->post('password'));
                $register_form->status = 1;
                $register_form->addTime = time();
                if($register_form->save(false)){
                        return $this->redirect(['user/login']);
                }else{
                    $data = array('message'=>$register_form->getErrors(),'url'=>'user/register');

                    return $this->render("@app/views/blog/error",['data'=>$data]);
                }
            }else{
                $data = array('message'=>$register_form->getErrors(),'url'=>'user/register');

               return $this->render("@app/views/blog/error",['data'=>$data]);
            }
        }else{
            return $this->render("register");
        }
    }
    public function actionLogin(){
        if(\Yii::$app->request->isPost){
            $login_model = new LoginForm();
            $login_model->username = \Yii::$app->request->post('username');
            $login_model->password = \Yii::$app->request->post('password');
            if(!$login_model->login()){
                print_r($login_model->getErrors());
            }else{
                
                //echo \Yii::$app->user->isGuest;
                //exit;
                $this->redirect(['blog/index']);
            }
            
        }else{
            return $this->render("login");
        }

    }

    public function actionLogout(){
        if(\Yii::$app->user->logout()){
            $this->redirect(['user/login']);
        }
    }
    
    public function actionTest(){
        echo Url::to(['user/index'])."<br>";
        echo Url::toRoute("user/index");
    }
}